import {messages} from "share/common";
import React from 'react';
import { connect } from 'react-redux'
import config from 'config'
import { Modal, Button, Tabs, Upload, Icon, message, Table } from 'antd'
const TabPane = Tabs.TabPane;
import httpFetch from 'share/httpFetch'
import FileSaver from 'file-saver'
const { confirm } = Modal;

//数据导入组件
class UploadResult extends React.Component {

  componentDidMount() {
    const { onRef } = this.props;
    onRef && (onRef(this));
  }

  //下载错误信息
  downloadErrors = () => {
    let { uploadResultOptions: { templateName, downFileExtension, errorUrl, errorParams, queryMode, method = 'get', userImportResponse = false }, transactionOID, importResponse = {} } = this.props;
    message.loading(messages('common-1.key378')/*正在生成文件..*/);
    let url = userImportResponse ? errorUrl : `${errorUrl}${queryMode ? `?transactionOID=${transactionOID}` : `/${transactionOID}`}`;
    let params = userImportResponse ? importResponse : (errorParams ? errorParams : {})
    httpFetch[method](url, params, {}, {responseType: 'arraybuffer'}).then(res => {
      let b = new Blob([res.data], {type: "file"});
      let name = (templateName || '') + messages('common-1.key372')/*错误信息*/;
      FileSaver.saveAs(b, `${name}.${downFileExtension || 'xlsx'}`);
    }).catch(() => {
      message.error(messages('common-1.key379')/*错误信息下载失败，请检查导入模板是否正确*/);
    })
  };

  //切换导入Tab页
  switchingTab = (tab) => this.props.onChange({ tabKey: tab });

  render() {
    const { asyncMode, asyncModeMessage, uploadResult, errorData, pagination, transactionOID, errorColumns,
      parseUploadResult, uploadResultOptions: { shouldDownloadErrorInfo, reimportable,
        getErrorTableVisible } } = this.props;
    let errorTableVisible = getErrorTableVisible ?
      getErrorTableVisible(uploadResult) :
      (uploadResult && uploadResult.failureEntities > 10);
    return (
      <div className='result'>
        {
          asyncMode ?
            asyncModeMessage :
              React.isValidElement(errorData) ?
                errorData :
                (
                  <div>
                    {
                      uploadResult &&
                        <p>
                          {parseUploadResult(uploadResult)}
                          {shouldDownloadErrorInfo && uploadResult.failureEntities > 0 && (
                            <Button
                              icon="download"
                              className='result-download-btn'
                              onClick={() => this.downloadErrors()}
                            >
                              {messages('common-1.key380')/*下载错误信息*/}
                            </Button>
                          )}
                        </p>
                    }
                    {reimportable && errorTableVisible &&
                      <p onClick={()=>this.switchingTab('TEMPLATE')} className='result-download-reimport'>
                        {messages('common-1.key381')/*请修改相应数据后，重新导入*/}
                      </p>}
                    {errorTableVisible &&
                      errorData && errorData.length ? (
                        <Table
                          rowKey={(record, index) => `${record.index}${index}`}
                          columns={errorColumns}
                          dataSource={errorData}
                          pagination={transactionOID && pagination.total > 10 ? pagination : false}
                          scroll={{x: 'max-content', y: 170}}
                          bordered
                          size="small"
                        />
                    ) : null}
                  </div>)
        }
      </div>
    );
  }
}

UploadResult.propTypes = {
  asyncModeMessage: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.node]), //异步导入的结果提示
  uploadResult: React.PropTypes.object, //导入结果
  errorData: React.PropTypes.oneOfType([React.PropTypes.array, React.PropTypes.object]), //导入结果的详细错误信息
  asyncMode:  React.PropTypes.bool,  //是否是异步导入模式
  uploadResultOptions: React.PropTypes.object //错误信息展示相关配置
};

UploadResult.defaultProps = {
  asyncModeMessage: messages('common-1.key382')/*导入进行中，请稍后查看结果*/,
  uploadResult: [],
  errorData: [],
  asyncMode: false,
  uploadResultOptions: {}
};

function mapStateToProps() {
  return {}
}

export default connect(mapStateToProps)(UploadResult);
